import 'dart:convert';
import 'dart:io';

import 'package:archive/archive_io.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';

/// 文件操作工具类
class FileUtil {
  /// 获取临时缓存目录
  static Future<String> getTempDirPath() async {
    var path = (await getTemporaryDirectory()).path;
    if (!path.endsWith('/')) {
      return '$path/';
    }
    return path;
  }

  /// 获取临时下载目录
  static Future<String> getTempDownloadPath() async {
    var tempPath = await getTempDirPath();
    var downloadDir = '${tempPath}Download/';
    await mkDirs(downloadDir);
    return downloadDir;
  }

  /// 创建文件夹
  static mkDirs(String dirPath) async {
    Directory dir = Directory(dirPath);
    try {
      bool exists = await dir.exists();
      if (!exists) {
        await dir.create();
      }
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }

  /// 清理下载目录
  static clearDownloadCache() async {
    var path = await getTempDownloadPath();
    File file = File(path);
    await file.delete(recursive: true);
  }

  /// 读取文件成字符串
  static Future<String> readFileAsString(String filePath,
      {Encoding encoding = utf8}) async {
    var file = File(filePath);
    if (file.existsSync()) {
      return file.readAsStringSync(encoding: encoding);
    }
    return '';
  }

  /// 解压assets目录的zip文件
  static unZipAssetsFile(
      String bundleZipPath, String fileName, String unZipDirPath) async {
    var data = await rootBundle.load(bundleZipPath);
    List<int> bytes =
        data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    var downloadPath = await FileUtil.getTempDownloadPath();
    var newPath = '$downloadPath$fileName';
    File file = File(newPath);
    //zip文件先存到文件系统
    await file.writeAsBytes(bytes);
    //然后解压
    await extractFileToDisk(newPath, unZipDirPath);
  }

  /// 文件是否存在
  static bool existFile(String filePath) {
    File file = File(filePath);
    return file.existsSync();
  }

  /// 文件夹是否存在
  static bool existDir(String dirPath) {
    Directory file = Directory(dirPath);
    return file.existsSync();
  }
}
